package servlet;

import bean.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;

/*
    实现查看的功能
 */
@WebServlet("/listStudentServlet")
public class listStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建一个字符输入流对象,关联相关的文件
        BufferedReader br=new BufferedReader(new FileReader("E:\\JavaProject\\" +
                "IdeaProjects\\JavaWeb\\reqresp_test\\stu.txt"));

        //2.创建一个集合对象,保存Student对象
        ArrayList<Student>stuList=new ArrayList<>();

        //3.循环读取文件中的数据,将数据封装到Student对象中,在把多个学生对象添加到集合中
        String line;
        while ((line=br.readLine())!=null){
            //张三,18,95
            Student stu=new Student();
            String[] arr = line.split(",");
            stu.setUsername(arr[0]);
            stu.setAge(Integer.parseInt(arr[1]));
            stu.setScore(Integer.parseInt(arr[2]));
            stuList.add(stu);
        }

        //4.遍历集合,将数据响应到浏览器
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = resp.getWriter();
        for (Student s : stuList) {
            pw.write(s.getUsername()+","+s.getAge()+","+s.getScore());
            pw.write("<br>");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
